<template>
  <div class="auto-reply-manage">
    <div class="toolbar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索关键词"
          style="width: 300px;"
          @keyup.enter.native="fetchAutoReplies"
      />
      <el-button type="primary" @click="openAddDialog">新增自动回复</el-button>
    </div>
    <el-table :data="autoReplies" style="width: 100%; margin-top: 20px;" stripe>
      <el-table-column prop="reply_id" label="ID" width="80"></el-table-column>
      <el-table-column prop="keyword" label="关键词"></el-table-column>
      <el-table-column prop="reply_content" label="回复内容"></el-table-column>
      <el-table-column prop="platform" label="平台" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="100"></el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" ref="formRef" label-width="80px">
        <el-form-item label="关键词">
          <el-input v-model="form.keyword"></el-input>
        </el-form-item>
        <el-form-item label="回复内容">
          <el-input type="textarea" v-model="form.reply_content"></el-input>
        </el-form-item>
        <el-form-item label="平台">
          <el-select v-model="form.platform" placeholder="请选择平台">
            <el-option label="web" value="web"></el-option>
            <el-option label="wechat" value="wechat"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" value="启用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const autoReplies = ref([])
const searchKeyword = ref('')

const dialogVisible = ref(false)
const dialogTitle = ref('新增自动回复')
const form = reactive({
  reply_id: null,
  keyword: '',
  reply_content: '',
  platform: '',
  status: '启用'
})
const formRef = ref(null)

// 获取自动回复规则列表，使用 fetch 请求数据
const fetchAutoReplies = async () => {
  try {
    let url = 'http://8223yt8md244.vicp.fun/api/auto_replies'
    if (searchKeyword.value.trim() !== "") {
      url += '?q=' + encodeURIComponent(searchKeyword.value.trim())
    }
    const res = await fetch(url)
    const data = await res.json()
    if (res.ok) {
      autoReplies.value = data.auto_replies
    } else {
      ElMessage.error(data.error || '获取自动回复数据失败')
    }
  } catch (error) {
    console.error('获取自动回复数据失败', error)
    ElMessage.error('获取自动回复数据失败')
  }
}

const openAddDialog = () => {
  dialogTitle.value = '新增自动回复'
  form.reply_id = null
  form.keyword = ''
  form.reply_content = ''
  form.platform = ''
  form.status = '启用'
  dialogVisible.value = true
}

const openEditDialog = (row) => {
  dialogTitle.value = '编辑自动回复'
  form.reply_id = row.reply_id
  form.keyword = row.keyword
  form.reply_content = row.reply_content
  form.platform = row.platform
  form.status = row.status
  dialogVisible.value = true
}

// 提交新增或编辑请求，使用 fetch 请求数据
const handleSubmit = async () => {
  try {
    if (!form.keyword || !form.reply_content || !form.platform) {
      ElMessage.warning('请填写完整信息')
      return
    }
    let res, data
    if (form.reply_id) {
      // 编辑操作
      res = await fetch(`http://8223yt8md244.vicp.fun/api/auto_replies/${form.reply_id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form)
      })
      data = await res.json()
      if (res.ok) {
        ElMessage.success('更新成功')
      } else {
        ElMessage.error(data.error || '更新失败')
      }
    } else {
      // 新增操作
      res = await fetch('http://8223yt8md244.vicp.fun/api/auto_replies', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form)
      })
      data = await res.json()
      if (res.ok) {
        ElMessage.success('新增成功')
      } else {
        ElMessage.error(data.error || '新增失败')
      }
    }
    dialogVisible.value = false
    fetchAutoReplies()
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该自动回复规则吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await fetch(`http://8223yt8md244.vicp.fun/api/auto_replies/${row.reply_id}`, {
        method: 'DELETE'
      })
      const data = await res.json()
      if (res.ok) {
        ElMessage.success('删除成功')
        fetchAutoReplies()
      } else {
        ElMessage.error(data.error || '删除失败')
      }
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
  })
}

onMounted(() => {
  fetchAutoReplies()
})
</script>

<style scoped>
.auto-reply-manage {
  padding: 20px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 20px;
}
</style>
